package com.youmu.shop.user.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.shop.weixin.pojo.SNSUserInfo;
import org.shop.weixin.util.AdvancedUtil;
import org.shop.weixin.util.EmojiFilterUtils;
import org.shop.weixin.util.WeixinOauth2Token;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.youmu.shop.admin.service.AdminService;
import com.youmu.shop.common.utils.ConfigUtil;
import com.youmu.shop.common.utils.WeixinToolUtil;
import com.youmu.shop.context.utils.UserContext;
import com.youmu.shop.coupon.service.CouponService;
import com.youmu.shop.system.bean.Admin;
import com.youmu.shop.system.bean.MemberRank;
import com.youmu.shop.system.vo.UserInfo;
import com.youmu.shop.user.service.UserService;
import com.youmu.shop.weixin.vo.WeixinInfo;

/**
 * 授权后的回调请求处理
 *
 * @author
 * @date 2013-11-12
 */

@Controller("OAuthController")
@RequestMapping("/OAuth")
public class OAuthController {
    
    private static Logger log = LoggerFactory.getLogger(OAuthController.class);
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CouponService couponService;
    
    @Autowired
    private AdminService adminService;
    
    /**
     * 前端请求微信获取用户信息的方式授权登录
     * @return
     */
    @SuppressWarnings("deprecation")
	@RequestMapping(value = "authForLoginByWeixin", method = RequestMethod.GET)
    public @ResponseBody Object authForLoginByWeixin(){
    	StringBuffer sb = new StringBuffer();
    	WeixinInfo weixinInfo = new WeixinInfo();
    	Map<String, Object> map = new HashMap<String, Object>();
    	map.put("appid", ConfigUtil.getWeixinAppId());
    	map.put("redirect_uri", URLEncoder.encode(ConfigUtil.getLocalDomain() + ConfigUtil.getWeixinAuthRedirectUrl()));
    	map.put("response_type", ConfigUtil.getWeixinResponseType());
    	map.put("scope", ConfigUtil.getWeixinScope());
//    	map.put("state", null);
    	sb.append(ConfigUtil.getWeixinAuthUrl()).append(WeixinToolUtil.getRequestParams(map)).append(ConfigUtil.getWechatRedirect());
    	weixinInfo.setAuthForLoginUrl(sb.toString());
    	return weixinInfo;
    }
    
    /**
     * 微信网页用户授权回调页面
     * @param request
     * @param response
     * @param model
     * @param session
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "auth",method = RequestMethod.GET)
    public String doGet(HttpServletRequest request, HttpServletResponse response, ModelMap model, HttpSession session) throws ServletException, IOException {
    	/**
    	 * 先判断用户是否同意授权
    	 */
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        log.info("用户已完成授权操作--------：code : " + code + " state : " + state);
        Boolean userAgreeAuth = !StringUtils.isEmpty(code);
        log.info("用户是否同意授权--" + userAgreeAuth);
        /**
         *  用户同意授权
         */
        if (userAgreeAuth) {
            /**
             * 获取网页授权access_token
             */
            log.info("进入商城端授权页面--------用户同意授权的code数据--" + code);
            WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken(ConfigUtil.getWeixinAppId(), ConfigUtil.getWeixinAppSecre(), code);
            if(weixinOauth2Token == null){
            	return "redirect:/dispatching/no-permission.html";
            }
            // 网页授权接口访问凭证
            String accessToken = weixinOauth2Token.getAccessToken();
            log.info("进入商城端授权页面--------用户同意授权的code数据获取网页授权接口访问凭证--" + accessToken);
            // 用户标识
            String openId = weixinOauth2Token.getOpenId();
            log.info("进入商城端授权页面--------用户openID--" + openId);
            // 获取用户信息
            SNSUserInfo snsUserInfo = AdvancedUtil.getSNSUserInfo(accessToken, openId);
            
            log.info("进入商城端授权页面--------用户昵称--" + snsUserInfo.getNickname());

            log.info("进入商城端授权页面--------从微信端返回的用户名为：" + EmojiFilterUtils.filterEmoji(snsUserInfo.getNickname()));

            //member验证和存入session           
            String toUri = request.getParameter("to");

            log.info("进入商城端授权页面--------用户openID会员登录方法验证成功--前往的页面为--" + toUri);
            if(StringUtils.isEmpty(state)){
            	UserInfo userInfo = userService.findUserInfoByOpenId(snsUserInfo.getOpenId());
            	if(userInfo!=null/*，根据snsUserInfo.getopenid()查询会员是否存在，会员存在*/ ){
            		//跳转到请求的跳转页面
            		log.error("从数据库获取到用户信息，保存在session中，userId为：" + userInfo.getId());
            		if(userInfo.getIsEnable()){
            			//用户可用，保存session
            			UserContext.setUserInfo(userInfo);
            			return "redirect:/#/index";
            		}else{
            			//未授权，跳转到未授权页面
            			return "redirect:/dispatching/no-permission.html";
            		}
            	}else {
            		//如果用户不存在，新增微信用户，发送优惠劵，将用户信息存入session，用户信息从snsUserInfo获取
            		UserInfo userInfo1 = new UserInfo();
            		userInfo1.setUsername(snsUserInfo.getOpenId());
            		userInfo1.setName(snsUserInfo.getNickname());
            		userInfo1.setWeixinPic(snsUserInfo.getHeadImgUrl());
            		userInfo1.setMemberRank("1");
            		userInfo1.setPoint("0");
            		userInfo1.setTotalPoint("0");
            		userInfo1.setSex(snsUserInfo.getSex());
            		userInfo1.setIsEnable(true);
            		userInfo1.setRegisterIp(request.getRemoteAddr());
            		userInfo1.setAddress(snsUserInfo.getProvince() + snsUserInfo.getCity());
            		userService.saveUserInfo(userInfo1);
            		log.error("用户不存在，生成一个用户信息，保存在session中,为：" + userInfo1);
            		
            		UserContext.setUserInfo(userInfo1);
            		
            		//遍历所有优惠劵，针对每个优惠劵种类生成一个对应用户id
            		List<Long> couponIds = couponService.findUsefulCouponIds();
            		for (Long id : couponIds) {
            			couponService.saveCouponForUser(id,userInfo1.getId());
            		}
            		//跳转商城主页
            		return "redirect:/#/index";
            	}
            }else{
            	log.info("登录用户为配送人员==============且同意授权");
            	Admin admin = adminService.selectAdminByUserNameForDispatching(snsUserInfo.getOpenId());
            	if(admin != null){
            		Admin checkAdmin = adminService.checkAdminDispatchingType(admin);
            		/**
            		 * 判断是否可用
            		 */
            		if(admin.getIsEnabled() && checkAdmin.getDispatchingType() != null){
            			log.info("配送人员存在==============名称为" + snsUserInfo.getNickname());
            			UserContext.setAdminInfo(admin);
            			return "redirect:/dispatching/#/index";
            		}else{
            			return "redirect:/dispatching/no-permission.html";
            		}
            	}else{
            		log.info("配送人员不存在，则新增后台配送人员==============名称为" + snsUserInfo.getNickname());
            		Admin newAdmin = new Admin();
            		newAdmin.setUsername(snsUserInfo.getOpenId());
            		newAdmin.setName(snsUserInfo.getNickname());
            		newAdmin.setWeixinPic(snsUserInfo.getHeadImgUrl());
            		newAdmin.setIsEnabled(true);
            		newAdmin.setCreateDate(new Date());
            		newAdmin.setModifyDate(new Date());
            		newAdmin.setIsBackUser(false);
            		newAdmin.setIsLocked(false);
            		adminService.insertSelective(newAdmin);
            		UserContext.setAdminInfo(newAdmin);
            		return "redirect:/dispatching/#/index";
            	}
            }
        } 
            //未授权，跳转到未授权页面
            return "redirect:/dispatching/no-permission.html";
    }

}
